package cn.hamster3.mc.plugin.ball.velocity.api;

import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.ball.common.entity.BallServerType;
import cn.hamster3.mc.plugin.ball.velocity.HamsterBallPlugin;
import cn.hamster3.mc.plugin.core.common.config.ConfigSection;
import cn.hamster3.mc.plugin.core.common.config.YamlConfig;
import com.velocitypowered.api.proxy.config.ProxyConfig;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.logging.Logger;

@SuppressWarnings("unused")
public final class CoreVelocityAPI extends BallAPI {
    public CoreVelocityAPI(@NotNull ConfigSection config) {
        super(config, BallServerType.PROXY);
    }

    public static CoreVelocityAPI getInstance() {
        return (CoreVelocityAPI) instance;
    }

    public static void init(@NotNull File configFile) throws IOException {
        if (instance != null) {
            return;
        }
        YamlConfig config = YamlConfig.load(configFile);
        instance = new CoreVelocityAPI(config);
    }

    @Override
    public void enable() throws SQLException, InterruptedException {
        ProxyConfig config = HamsterBallPlugin.getInstance().getProxyServer().getConfiguration();
        try {
            Field field = config.getClass().getDeclaredField("bind");
            field.setAccessible(true);
            String bind = (String) field.get(config);
            int i = bind.lastIndexOf(":");
            String substring = bind.substring(i + 1);
            instance.getLocalServerInfo().setHost(bind.substring(0, i));
            instance.getLocalServerInfo().setPort(Integer.parseInt(substring));
        } catch (Exception e) {
            HamsterBallPlugin.getInstance().getSlf4jLogger().error("获取 Velocity 监听端口时遇到了一个异常", e);
        }
        super.enable();
    }

    @Override
    public void disable() throws SQLException, InterruptedException {
        super.disable();
    }

    @Override
    public @NotNull Logger getLogger() {
        return HamsterBallPlugin.getInstance().getLogger();
    }
}
